package com.rh.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.rh.dto.Result;
import com.rh.entity.po.User;
import com.rh.handler.UserHandler;
import com.rh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@CrossOrigin
public class ExcelController {
    @Autowired
    private UserService userService;

    /**
     * 上传
     */
    @PostMapping("/uploadExcel")
    public Result uploadExcel(@RequestParam("file") MultipartFile file) throws IOException {
        System.out.println("上传");
        String fileName=file.getOriginalFilename();
        System.out.println("文件名:"+fileName);
        EasyExcel.read(file.getInputStream(), User.class, new AnalysisEventListener<User>() {
            //解析每一行数据
            @Override
            public void invoke(User user, AnalysisContext analysisContext) {
                System.out.println(user);
                userService.addUser(user);
            }
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                System.out.println("解析完成");
            }
        }).sheet().doRead();
        Result result = new Result();
        return result;
    }
    /**
     * 文件下载
     */
    @RequestMapping(value = "/downLoad")
    public void downLoad(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //文件名
        String fileName="abc.xlsx";
        response.setHeader("Content-disposition","attachment;filename="+fileName);
        EasyExcel.write(response.getOutputStream(),User.class).sheet("用户").doWrite(userService.queryUser());
    }

}
